<?php

namespace App\Console\Commands;

use App\Http\Models\PigsFarm;
use App\Http\Models\PigsFarmsPm;
use App\Http\Models\Region;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class CollectPm extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'CollectPm';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 采集pm2.5数据，需要做成每小时定时任务
     * @return mixed
     */
    public function handle()
    {
        $all_farm = PigsFarm::all();
        foreach ($all_farm as $f) {
            $id_arr = explode(',', $f->address_code);
            $region = Region::getRegionGroup($id_arr[3]);
            $code = $region[3]->code;
            $region_name = $region[3]->region_name;
            $region_id = $region[3]->region_id;
            if (empty($code)) {
                $code = $region[2]->code;
                $region_name = $region[2]->region_name;
                $region_id = $region[2]->region_id;
            }
            $url = "http://api.help.bj.cn/apis/aqi2/?id={$code}";
            $pm = curl_request($url);

            if ($pm['status']) {//区级没有获取到，则获取地级
                $code = $region[2]->code;
                $region_name = $region[2]->region_name;
                $region_id = $region[2]->region_id;
                $url = "http://api.help.bj.cn/apis/aqi2/?id={$code}";
                $pm = curl_request($url);
            }

            Log::info('每小时采集pm2.5 :url'.$url);
            if ($pm['status']) {//接口报错
                Log::info('采集pm2.5 失败');
            } else {
                $pm2_5 = $pm10 = 0;
                foreach ($pm['data'] as $d) {
                    if ($d['en'] == 'PM2.5') {
                        $pm2_5 = $d['val'];
                    }
                    if ($d['en'] == 'PM10') {
                        $pm10 = $d['val'];
                    }
                }
                $data = [
                    'region_name'   => $region_name,
                    'region_id'     => $region_id,//地区ID
                    'val'           => $pm['val'],
                    'lev'           => $pm['lev'],
                    'impx'          => $pm['impx'],
                    'pm2_5'         => $pm2_5,
                    'pm10'          => $pm10,
                    'update'        => $pm['updata'],
                    'pm_info'       => json_encode($pm, JSON_UNESCAPED_UNICODE),
                ];
                $pm_id = PigsFarmsPm::insertGetId($data);
                Log::info('每小时采集pm2.5 ID：'.$pm_id);
            }
        }
    }
}
